package com.hatom.cameraxhelp.widgets;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.internal.utils.ImageUtil;

import com.blankj.utilcode.util.ImageUtils;
import com.hatom.cameraxhelp.R;

import java.util.ArrayList;
import java.util.Objects;


/**
 * @author tangxianfeng
 * Created on 2022/04/22
 * desc   : 多人脸框View
 * 进行下方列表显示封装 可进行添加下方图片的点击监听 faceClickListener
 */
public class MultFaceView extends RelativeLayout {

    private final Context mContext;

    private MultFaceBorderView faceShowView;//识别框
    private AppCompatTextView img_resulttext;//存放识别结果
    private LinearLayout img_reshow;//重新识别img展示
    private LinearLayout small_linear;//存放人脸小图的容器
    private ArrayList<Bitmap> showBitmaps=new ArrayList<>();//小图bitmap
    private FaceClickListener faceClickListener;//下方人脸图片的点击监听

    private int faceNum=10;//要识别的人脸数

    public MultFaceView(Context context) {
        this(context, null);
    }

    public MultFaceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MultFaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext=context;
        init();
    }

    private void init() {
        // 防止不支持硬件加速的设备，绘制后黑屏
        View finalview=View.inflate(mContext, R.layout.camerax_fragment_face_camera,this);//集成布局
        initView(finalview);

    }

    //点击人脸图监听
    public void setFaceClickListener(FaceClickListener faceClickListener) {
        this.faceClickListener = faceClickListener;
    }

    //布局 监听init
    private void initView(View view) {
        faceShowView =  view.findViewById(R.id.faceshow);
        img_reshow=view.findViewById(R.id.img_reshow);
        img_resulttext=view.findViewById(R.id.img_resulttext);
        img_reshow.setVisibility(View.GONE);
        findViewById(R.id.face_camera_preview).setVisibility(GONE);
        findViewById(R.id.trans_camera).setVisibility(GONE);
        small_linear=view.findViewById(R.id.small_linear);

        img_reshow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recycleoldBit();
                small_linear.removeAllViews();
                img_reshow.setVisibility(View.GONE);
                img_resulttext.setText("");
            }
        });
        faceShowView.setGetMultFace(new MultFaceBorderView.GetMultFace() {
            @Override
            public void stayface(final ArrayList<Bitmap> bitmaps) {
                if (bitmaps==null){
                    return;
                }
                recycleoldBit();
                showBitmaps=bitmaps;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        small_linear.removeAllViews();
                        for (int i=0;i<bitmaps.size();i++){
                            AddImage(i);
                        }
                        img_reshow.setVisibility(View.VISIBLE);
                        String result= "一共识别到" + bitmaps.size() + "条结果";
                        img_resulttext.setText(result);
                    }
                });
                //isStartFaceAnalye=false;//暂停识别
            }//停留次数过多 进行小图展示 用户对此人脸比较确信

            @Override
            public void getprogress(int progress) {

            }
        });

    }
    //回收之前的bitmap图片
    private void recycleoldBit(){
        if (showBitmaps!=null){
            for (Bitmap bitmap:showBitmaps){
                bitmap.recycle();
            }//回收之前的图片组
        }
    }

    //添加人脸图到列表
    private void AddImage(int postion){
        ImageView imageView=new ImageView(mContext);
        imageView.setImageBitmap(showBitmaps.get(postion));
        imageView.setLayoutParams(new ViewGroup.LayoutParams(dip2px(100),dip2px(100)));
        if (faceClickListener!=null){
            addlistener(imageView,postion);
        }//未添加就不进行绑定

        small_linear.addView(imageView);
    }
    //绑定监听
    private void addlistener(ImageView imageView, final int postion){
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (faceClickListener!=null){
                    faceClickListener.clickface(postion);
                    faceClickListener.clickface(getBitmapByPostion(postion));
                }//再次判断 避免使用中给设置为null
            }
        });//跳转详情页 单人脸
    }

    //DP转换
    public int dip2px( float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public void detect(ImageProxy imageProxy){
        if (img_reshow.getVisibility()==View.GONE){//当重新识别不可见时进行识别
            detectFaceByPhoneSystem(imageProxy);//执行人脸识别
        }else {
            faceShowView.removeRect();//移除原识别框
        }
    }

    @SuppressLint("RestrictedApi")
    public void detectFaceByPhoneSystem(@NonNull ImageProxy imageProxy) {
        Bitmap rgbBitmap = null;
        try {
            rgbBitmap = ImageUtils.getBitmap(Objects.requireNonNull(ImageUtil.yuvImageToJpegByteArray(imageProxy, new Rect(0, 0, imageProxy.getWidth(), imageProxy.getHeight()), 80)), 0)
                    .copy(Bitmap.Config.RGB_565, true);
        } catch (ImageUtil.CodecFailedException e) {
            e.printStackTrace();
        }

        // 获取数据旋转角
        int rotate = imageProxy.getImageInfo().getRotationDegrees();

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            rotate=rotate+90;
        }
        Bitmap bitmap = ImageUtils.rotate(rgbBitmap, rotate, 0, 0);

        assert bitmap != null;
        float scaleX = (float) getMeasuredWidth() / bitmap.getWidth();
        float scaleY = (float) getMeasuredHeight() / bitmap.getHeight();
        FaceDetector detector = new FaceDetector(bitmap.getWidth(), bitmap.getHeight(), faceNum);
        FaceDetector.Face[] faces = new FaceDetector.Face[faceNum];
        int number = detector.findFaces(bitmap, faces);

        if (number > 0) {
            faceShowView.updateFaces(faces, scaleX, scaleY, number, bitmap);
        } else {
            faceShowView.removeRect();
        }
    }

    //设置要识别的人脸数量
    public void setFaceNum(int faceNum) {
        this.faceNum = faceNum;
    }

    //设置最大停留次数
    public void setMaxStayTime(int times){
        faceShowView.setMaxStayTime(times);
    }

    //通过位置获取bitmap图片
    public Bitmap getBitmapByPostion(@Nullable int postion){
        if (showBitmaps!=null&&showBitmaps.size()>postion){
            return showBitmaps.get(postion);
        }
        return null;
    }

    public interface FaceClickListener{
        void clickface(Bitmap bitmap);//点击下方人脸返回
        void clickface(int postion);//点击下方人脸的位置
    }
}
